import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/forkJoin'
import { Park } from './park';

@Injectable()
export class ParkDataProvider {
  private readonly baseUrl: string = 'https://api.bmob.cn/1';
  private readonly httpHeaders : HttpHeaders = new HttpHeaders({
    'X-Bmob-Application-Id':'03b525f1b6bc7bd1ba3528b708d9c1b4',
    'X-Bmob-REST-API-Key':'183cbb38f271a1d1dfe0ce70884f8ad2',
    'Content-Type':'application/json',
  })

  constructor(public http: HttpClient) {
  }

  /**
   * 分页获取景区数据
   * @param num 
   * @param page 
   */

  getParks(num: number, page: number): Observable<Park[]>{
    let _params = new HttpParams()
    .set('limit', `${num}`)
    .set('skip', `${(page - 1)* num}` );
    return this.http.get<Park[]>(`${this.baseUrl}/classes/parks`,
    {headers: this.httpHeaders, params: _params}).map(_=>_['results']);
  }


  /**
   * 获取记录条数
   */
  getCount(): Observable<number>{
    return this.http.get<number>(`${this.baseUrl}/classes/parks?limit=0&count=1`, 
    {headers: this.httpHeaders}).map(data=>data['count']);
  }


  /**
   * 获取所有记录
   * @param total 记录总数
   */
  getAllParks(total: number): Observable<Park[][]> {
    let num = 200;
    let all: Observable<Park[]>[] = [];
    for (let index = 0; index <= total / num; index++){
      let _params = new HttpParams()
      .set('limit', `${num}`)
      .set('skip', `${index * num}` );
      all[index] = this.http.get<Park[]>(`${this.baseUrl}/classes/parks`,
      { headers: this.httpHeaders, params: _params }).map(_ => _['results']);
    }
    return Observable.forkJoin(all);
  }

}
